<?php

namespace app\videos\server;

use app\common\server\Service;
use app\videos\model\Analysis as AnalysisModel;
use one\Http;

class Analysis extends Service
{

    public function initialize()
    {
        parent::initialize();
        if (!isset($this->serviceKey) || empty($this->serviceKey) || cache('serviceKey') != $this->serviceKey) {
            exit(json_encode(['msg' => '非法操作！', 'code' => 712]));
        }
        $this->AnalysisModel = new AnalysisModel();
    }
    /**
     * 解析地址，并记录
     *
     * @param [type] $data
     * @param [type] $user
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function getAnalysis($data, $user)
    {
        if (empty($data['url'])) {
            $this->error = '播放地址不能为空';
            return false;
        }
        $base64_url = str_replace('"', '', base64_urlSafeDecode($data['url']));
        $base64_url = urldecode($base64_url);
        if (!empty($base64_url)) {
            $data['url'] = $base64_url;
        }
        // 白名单关键字
        $white_list = config('video.analysis_white_list');
        $white_list = trim($white_list);
        $white_list = explode("\n", $white_list);
        $is_do = true;
        foreach ($white_list as $v) {
            if (strstr($data['url'], $v)) {
                $is_do = false;
                break;
            }
        }
        if ($is_do) {
            return $this->urlFormat($data);
        }
        return $data['url'];
    }

    public function urlFormat($data)
    {
        $res = cache(md5($data['url']));
        // if ($res) {
        //     return $res;
        // }
        $api_url = config("video.analysis_api_url");
        $ret = Http::get($api_url . $data['url']);
        if (!is_string($ret)) {
            $this->error = '请求超时，请稍候再试';
            return false;
        }
        $ret = json_decode(ltrim($ret, "\XEF\XBB\XBF"), 1);
        if (empty($ret) || isset($ret['code']) && $ret['code'] != 200) {
            $this->error = '该影片无法播放';
            return false;
        }
        cache(md5($data['url']), $ret['url'], 300);
        return $ret['url'];
    }
}
